import datetime

from flask import Flask, render_template, request, jsonify, Response, session
from jieba.analyse import extract_tags
import time
import loginUtils
import utils, riskAreaUtils, areaDetailsUtils, historyUtils, hotSearchUtils, reportUtils, operateUtils, config, spider
import string
from os import urandom

app = Flask(__name__)
app.config.from_object(config)
app.secret_key = urandom(50)
app.permanent_session_lifetime = datetime.timedelta(seconds=60 * 60)


@app.route("/report")
def report():
    return render_template("report.html")


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/main')
def main():
    # 验证session
    email = session.get('email')
    if email:
        return render_template('main.html')
    else:
        return jsonify(msg='登录校验未通过')


@app.route('/risk_area')
def risk_area():
    return render_template('risk_area.html')


@app.route('/area_details')
def area_details():
    return render_template('area_details.html')


@app.route('/history')
def history():
    return render_template('history.html')


@app.route('/hotSearch')
def hotSearch():
    return render_template('hotSearch.html')


@app.route('/spider')
def spider():
    return render_template('spider.html')


@app.route('/report_areaCount')
def report_areaCount():
    return render_template('report_areaCount.html')


@app.route('/report_history')
def report_history():
    return render_template('report_history.html')


@app.route('/c1')
def get_c1_data():
    data = utils.get_c1_data()
    return jsonify({"confirm": data[0], "suspect": data[1], "heal": data[2], "dead": data[3]})


@app.route('/c2')
def get_c2_data():
    result = []
    for tup in utils.get_c2_data():
        result.append({"name": tup[0], "value": tup[1]})
    return jsonify({"data": result})


@app.route('/l1')
def get_l1_data():
    data = utils.get_l1_data()
    day, confirm_add, suspect_add, heal_add, dead_add = [], [], [], [], []
    for a, b, c, d, e in data:
        day.append(a)  # a是datatime类型
        confirm_add.append(b)
        suspect_add.append(c)
        heal_add.append(d)
        dead_add.append(e)
    return jsonify({"day": day, "confirm_add": confirm_add, "suspect_add": suspect_add, "heal_add": heal_add,
                    "dead_add": dead_add})


@app.route("/l2")
def get_l2_data():
    data = utils.get_l2_data()
    # end_update_time, province, city, county, address, type
    details = []
    risk = []
    end_update_time = data[0][0]
    for a, b, c, d, e, f in data:
        risk.append(f)
        details.append(f"{b}\t{c}\t{d}\t{e}")
    return jsonify({"update_time": end_update_time, "details": details, "risk": risk})


@app.route("/r1")
def get_r1_data():
    data = utils.get_r1_data()
    city = []
    confirm = []
    for k, v in data:
        city.append(k)
        confirm.append(int(v))
    return jsonify({"city": city, "confirm": confirm})


@app.route("/r2")
def get_r2_data():
    data = utils.get_r2_data()  # 格式 (('民警抗疫一线奋战16天牺牲1037364',), ('四川再派两批医疗队1537382',)
    d = []
    for i in data:
        k = i[0].rstrip(string.digits)  # 移除热搜数字
        v = i[0][len(k):]  # 获取热搜数字
        ks = extract_tags(k)  # 使用jieba 解析标签提取关键字
        for j in ks:
            if not j.isdigit():
                d.append({"name": j, "value": v})
    return jsonify({"kws": d})


# 注册
@app.route("/register", methods=["POST", "GET"])
def register():
    # 获取注册信息
    username = request.args.get("username")
    email = request.args.get("email")
    password = request.args.get("password")
    # 判断是否已经注册
    if loginUtils.is_registered(username, email):
        return jsonify({"status": False, "msg": "该用户已经注册"})
    # 注册
    if loginUtils.register(username, email, password):
        return jsonify({"status": True, "msg": "注册成功"})


# 登录
@app.route("/login", methods=["POST", "GET"])
def login():
    # 获取登录信息
    email = request.args.get("email")
    password = request.args.get("password")
    # 判断用户名密码是否正确
    if loginUtils.login(email, password):
        session['email'] = email
        session.permanent = True
        return jsonify({"status": True, "msg": "登录成功"})
    else:
        return jsonify({"status": False, "msg": "用户名或密码错误"})


# 获取用户名
@app.route("/getUsername")
def getUsername():
    email = session.get('email')
    if email:
        username = loginUtils.getUser(email)
        return jsonify({"status": True, "data": username})


# 退出登录
@app.route("/logout", methods=["POST", "GET"])
def logout():
    session.clear()
    return render_template('index.html')


# 风险地区
@app.route("/findAllRiskArea")
def findAllRiskArea():
    data = riskAreaUtils.findAll()
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})


@app.route("/findPageRiskArea", methods=["POST", "GET"])
def findPageRiskArea():
    data = request.get_json()
    if data['queryString'] == None:
        total = riskAreaUtils.findTotal()
        result = riskAreaUtils.findPage(data)
    else:
        total = riskAreaUtils.clickfindTotal(data['queryString'])
        result = riskAreaUtils.clickfindPage(data)
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": result, "total": total})


@app.route("/findRiskAreaByProvince")
def findRiskAreaByProvince():
    province = request.args.get("province")
    data = riskAreaUtils.findByProvince(province)
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})


@app.route("/deleteRiskArea")
def deleteRiskArea():
    id = request.args.get("id")
    try:
        riskAreaUtils.delete(id)
        return jsonify({"status": True, "msg": "删除成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "删除失败"})


@app.route("/addRiskArea", methods=["POST"])
def addRiskArea():
    data = request.get_json()
    try:
        riskAreaUtils.add(data)
        return jsonify({"status": True, "msg": "添加成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "添加失败"})


@app.route("/findRiskAreaById")
def findRiskAreaById():
    id = request.args.get("id")
    data = riskAreaUtils.findById(id)
    return jsonify({"status": True, "msg": "查询信息成功", "data": data})


@app.route("/editRiskArea", methods=["POST"])
def editRiskArea():
    data = request.get_json()
    try:
        riskAreaUtils.edit(data)
        return jsonify({"status": True, "msg": "修改成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "修改失败"})


@app.route("/getNewRiskAreaData")
def getNewRiskAreaData():
    try:
        spider.delete_risk_area()
        time.sleep(1)
        spider.update_risk_area()
        return jsonify({"status": True, "msg": "更新成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "更新失败"})


# 地区详细信息
@app.route("/findAllAreaDetails")
def findAllAreaDetails():
    data = areaDetailsUtils.findAll()
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})


@app.route("/findAreaDetailsByProvince")
def findAreaDetailsByProvince():
    province = request.args.get("province")
    data = areaDetailsUtils.findByProvince(province)
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})


@app.route("/findAreaDetailsById")
def findAreaDetailsById():
    id = request.args.get("id")
    data = areaDetailsUtils.findById(id)
    return jsonify({"status": True, "msg": "查询信息成功", "data": data})


@app.route("/editAreaDetails", methods=["POST"])
def editAreaDetails():
    data = request.get_json()
    data['update_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    try:
        areaDetailsUtils.edit(data)
        return jsonify({"status": True, "msg": "修改成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "修改失败"})


@app.route("/getNewAreaDetailsData")
def getNewAreaDetailsData():
    try:
        spider.delete_details()
        time.sleep(1)
        spider.update_details()
        return jsonify({"status": True, "msg": "更新成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "更新失败"})


# 历史数据
@app.route("/findAllHistory")
def findAllHistory():
    data = historyUtils.findAll()
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})


@app.route("/findHistoryById")
def findHistoryById():
    id = request.args.get("id")
    data = historyUtils.findById(id)
    return jsonify({"status": True, "msg": "查询信息成功", "data": data})


@app.route("/deleteHistory")
def deleteHistory():
    id = request.args.get("id")
    try:
        historyUtils.delete(id)
        return jsonify({"status": True, "msg": "删除成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "删除失败"})


@app.route("/editHistory", methods=["POST"])
def editHistory():
    data = request.get_json()
    data['ds'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    try:
        areaDetailsUtils.edit(data)
        return jsonify({"status": True, "msg": "修改成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "修改失败"})


@app.route("/getNewHistoryData")
def getNewHistoryData():
    try:
        spider.delete_history()
        time.sleep(1)
        spider.update_history()
        return jsonify({"status": True, "msg": "更新成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "更新失败"})


# 热门话题
@app.route("/findAllHotSearch")
def findAllHotSearch():
    data = hotSearchUtils.findAll()
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})


@app.route("/findHotSearchByWord")
def findHotSearchByWord():
    word = request.args.get("word")
    data = hotSearchUtils.findByWord(word)
    return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})


@app.route("/deleteHotSearch")
def deleteHotSearch():
    id = request.args.get("id")
    try:
        hotSearchUtils.delete(id)
        return jsonify({"status": True, "msg": "删除成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "删除失败"})


@app.route("/addHotSearch", methods=["POST"])
def addHotSearch():
    data = request.get_json()
    try:
        hotSearchUtils.add(data)
        return jsonify({"status": True, "msg": "添加成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "添加失败"})


@app.route("/findHotSearchById")
def findHotSearchById():
    id = request.args.get("id")
    data = hotSearchUtils.findById(id)
    return jsonify({"status": True, "msg": "查询信息成功", "data": data})


@app.route("/editHotSearch", methods=["POST"])
def editHotSearch():
    data = request.get_json()
    data['dt'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    try:
        hotSearchUtils.edit(data)
        return jsonify({"status": True, "msg": "修改成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "修改失败"})


@app.route("/getNewHotSearchData")
def getNewHotSearchData():
    try:
        spider.delete_hotsearch()
        time.sleep(1)
        spider.update_hotsearch()
        return jsonify({"status": True, "msg": "更新成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "更新失败"})


# 上次更新时间
@app.route("/findAllLastUpdate")
def findAllLastUpdate():
    try:
        data = operateUtils.findAll()
        return jsonify({"status": True, "msg": "查询所有信息成功", "data": data})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "查询所有信息失败"})


@app.route("/updateWithSpider")
def updateWithSpider():
    try:
        id = request.args.get("id")
        if id == 1:
            spider.delete_details()
            time.sleep(1)
            spider.update_details()
        elif id == 2:
            spider.delete_history()
            time.sleep(1)
            spider.update_history()
        elif id == 3:
            spider.delete_risk_area()
            time.sleep(1)
            spider.update_risk_area()
        elif id == 4:
            spider.delete_hotsearch()
            time.sleep(1)
            spider.update_hotsearch()
        email = session.get('email')
        if email:
            role = loginUtils.getUser(email)
        else:
            role = '系统自动更新'
        update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        data = {'id': id, 'update_time': update_time, 'role': role}
        operateUtils.edit(data)
        return jsonify({"status": True, "msg": "更新成功"})
    except Exception as e:
        print(e)
        return jsonify({"status": False, "msg": "更新失败"})


# 报表部分
@app.route("/areaCount")
def areaCount():
    province = request.args.get('province')
    if province != 'null':
        pass
    else:
        province = '福建'
    data = reportUtils.areaCount(province)
    city = []
    confirm = []
    for l in data:
        city.append(l['city'])
        confirm.append(int(l['confirm']))
    return jsonify({"city": city, "confirm": confirm})


@app.route("/areaPie")
def areaPie():
    province = request.args.get('province')
    if province != 'null':
        pass
    else:
        province = '福建'
    data = reportUtils.areaPie(province)
    return jsonify({"data": data})


if __name__ == '__main__':
    app.run(debug=True)
